/**
 * @Project : ProgrammingExercises
 * @Package : Leetcode
 * @File : Q0021.java
 * @Author : WangRuoyu
 * @Date 2022/12/24 19:15
 */

package leetcode;

import util.LinkList;
import util.ListNode;

public class Q0021 {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;

        if (list1.val > list2.val) {
            ListNode tmp = list1;
            list1 = list2;
            list2 = tmp;
        }

        ListNode h = new ListNode(-1, list1);
        ListNode pre = h;

        while (list1 != null && list2 != null) {
            if (list1.val > list2.val) {
                ListNode tmp = list2.next;
                list2.next = list1;
                pre.next = list2;
                list2 = tmp;
                pre = pre.next;
            } else {
                list1 = list1.next;
                pre = pre.next;
            }
        }

        if (list1 == null) {
            pre.next = list2;
        }

        return h.next;
    }

    public static void main(String[] args) {
        Q0021 sl = new Q0021();
        ListNode list1 = new ListNode(1, new ListNode(3, new ListNode(5)));
        ListNode list2 = new ListNode(2, new ListNode(4, new ListNode(6)));
        LinkList.printList(sl.mergeTwoLists(list1, list2));
    }
}

